import React, { useEffect, useState } from "react";
import { Modal, Form, Input, message, Button, Select } from "antd";
import { listProducts } from "../../../../api/ckgl";
const { Option } = Select;

interface WarehouseProductValues {
  product_id: number;
  warehouse_id: number;
  inventory: number;
  reminder_threshold: number;
}

interface WarehouseProductModalProps {
  title: string;
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  defaultValue?: any;
  warehouses: any[];
}

const WarehouseProductModal: React.FC<WarehouseProductModalProps> = ({
  title,
  visible,
  onCancel,
  onOk,
  defaultValue = {},
  warehouses = [],
}) => {
  const [form] = Form.useForm<WarehouseProductValues>();
  const warehouse_id = Form.useWatch("warehouse_id", form);
  const [loading, setLoading] = useState<boolean>(false);
  const [updateWarehouseIdNum, setUpdateWarehouseIdNum] = useState<number>(0);
  const [productList, setProductList] = useState<any[]>([]);

  useEffect(() => {
    // 这里更新对应的
    getListProducts();
  }, [warehouse_id]);

  const getListProducts = () => {
    setLoading(true);
    // 调用 listProducts API，并处理响应
    listProducts({
      page: 1,
      size: 300,
      warehouse_id: warehouse_id,
    })
      .then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        const { products, total } = res.data;
        setProductList(products);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
      form.resetFields();
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  useEffect(() => {
    if (loading) return;
    if (Object.keys(defaultValue).length === 0) {
      // if (updateWarehouseIdNum > 1) {
      //   return;
      // }
    } else {
      if (updateWarehouseIdNum > 1) {
        return;
      }
      form.setFieldsValue({
        ...defaultValue,
      });
      setUpdateWarehouseIdNum((n) => n + 1);
    }
  }, [defaultValue, visible, loading]);

  useEffect(() => {
    setUpdateWarehouseIdNum(0);
  }, [visible]);

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk} disabled={loading}>
          确定
        </Button>,
      ]}
    >
      <Form form={form}>
        <Form.Item
          label="选择仓库"
          name="warehouse_id"
          rules={[
            {
              required: !Object.keys(defaultValue).length,
              message: "请选择仓库",
            },
          ]}
        >
          {/* <Select
						placeholder="请选择分类"
						fieldNames={{
							label: "class_name",
							value: "class_id",
						}}
						options={classList}
					/> */}
          <Select placeholder="请选择仓库">
            {warehouses.map((ele) => (
              <Option key={ele.id} value={ele.id}>
                {ele.warehouse_name}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="物品"
          name="product_id"
          rules={[
            {
              required: true,
              message: "请输入有效的物品",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Select placeholder="请选择仓库">
            {productList.map((product) => (
              <Option key={product.id} value={product.id}>
                {product.product_name}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="库存"
          name="inventory"
          rules={[
            {
              required: true,
              message: "请输入有效的库存数量",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input type="number" placeholder="请输入库存数量" />
        </Form.Item>
        <Form.Item
          label="提醒阈值"
          name="reminder_threshold"
          rules={[
            {
              required: true,
              message: "请输入有效的提醒阈值",
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input type="number" placeholder="请输入提醒阈值" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default WarehouseProductModal;
